#!/usr/bin/perl

# fairly generic release tool for scripted projects
#  - for upload support, add ~/.googlecode-user and ~/.googlecode-pass
#    files with appropriate contents, and ensure you have a copy of
#    http://support.googlecode.com/svn/trunk/scripts/googlecode_upload.py
#    in the current directory.

# first check input tag dir is valid
$dir = $ARGV[0];
$dir =~ s/\/$//; # remove trailing slash
if(!(-d $dir)) {
 error("Could not find directory: $dir");
}

# now determine application name from parent dirname
chop($app = `cd .. && pwd`);
$app =~ s/^.*\///g;
if(!($app =~ /^[a-z0-9-]+$/)) {
 error("Unable to ascertain application name (came up with '$app')");
}

# add VERSION file
`echo "$dir" > $dir/VERSION`;

# calculate base name of release file
$filebasename = $app . '-' . $dir;

# generate temporary symlink to dir
$symdir = $filebasename;
`ln -s $dir $symdir`;

# generate tarball
print "Building tarball... ";
`tar --exclude .svn --exclude .git -chjf $filebasename.tar.bz2 $symdir`;
print "done.\n";

# generate zipfile
print "Building zipfile... ";
`zip --exclude '*.svn/*' '*.git/*' -9r $filebasename.zip $symdir`;
print "done.\n";

# remove symlinked dir
`rm $symdir`;

# access upload credentials
chop($gc_username = `cat ~/.googlecode-user 2>/dev/null`);
chop($gc_password = `cat ~/.googlecode-pass 2>/dev/null`);
# if we're good...
if(($gc_username ne '') && ($gc_password ne '')) {
 # upload tarball
 print "Uploading tarball... ";
 `./googlecode_upload.py -u '$gc_username' -w '$gc_password' -p '$app' -s '$app (v$dir) - Tar/Bz2 Format' -l 'Featured,Archive,OpSys-All' $filebasename.tar.bz2 1>/dev/null 2>/dev/null`;
 print "done.\n";
 # upload zipfile
 print "Uploading zipfile... ";
 `./googlecode_upload.py -u '$gc_username' -w '$gc_password' -p '$app' -s '$app (v$dir) - Zip Format' -l Featured,Archive,OpSys-All $filebasename.zip 1>/dev/null 2>/dev/null`;
 print "done.\n";
}

# warning
print "Don't forget to run:\n";
print " git add '$dir'\n";
print " git push\n";

# all done
exit(0);

sub error {
 print STDERR "ERROR: $_[0]\n";
 exit(1);
}
